package com.estar.integaration.Util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;


/**
 * Author: YJL
 * Date: 2021/12/5 13:03
 **/

public class ECDSAUtil {
  private final static Logger logger = LoggerFactory.getLogger(ECDSAUtil.class);

  public static byte[] decryptBASE64(String key) {
    return Base64.decodeBase64(key);
  }

  public static String encryptBASE64(byte[] key) {

    return Base64.encodeBase64String(key);

  }

  /**
   * 1、使用私钥执行签名
   * <p>Title: getPrivateKeySign</p>
   * <p>Description: </p>
   *
   * @param ecPrivateKey 私钥
   * @param plaintext    用于签名的明文
   * @return sign            返回签名
   * @author
   */
  public static String getPrivateKeySign(String ecPrivateKey, String plaintext) {
    try {
      byte[] privateKeyByte = decryptBASE64(ecPrivateKey);
      PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
      KeyFactory keyFactory = KeyFactory.getInstance("EC");
      PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
      Signature signature = Signature.getInstance("SHA1withECDSA");
      signature.initSign(privateKey);
      signature.update(plaintext.getBytes());
      byte[] res = signature.sign();//签名
      return encryptBASE64(res);
    } catch (Exception e) {
      logger.error("获取数字签名失败", e);
    }
    return null;
  }
}
